<template>
  <view class="share-page" :style="{ height: canvasHeight + 100 + 'px' }">
    <html2canvas v-if="show" ref="html2canvas" domId="#box" @renderFinish="renderFinish">
      <view
        id="box"
        class="share-page-box"
        :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
      >
        <view v-html="htmlToImage" />
      </view>
    </html2canvas>
    <view
      v-else
      class="share-page-box msg-box"
      :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    >
      {{ msg }}
    </view>
    <view v-if="shareImg" class="share-page-btn" @click="extraImage">
      <button class="btn-big" size="mini">保存图片</button>
    </view>
    <view v-else class="noneText">
      <text>图片已经上传到服务器</text>
    </view>
  </view>
</template>
<script>
import html2canvas from "@/components/html2canvas/html2canvas.vue";
import baseUrl from "@/request/baseUrl.js";
const { wxml, style } = require("./DomData.js");

export default {
  components: {
    html2canvas,
  },
  data() {
    return {
      show: false, // 是否显示canvas
      htmlToImage: null,
      canvasWidth: 595, // 默认canvas宽高
      canvasHeight: 842,
      screenWidth: 842, // 设备宽度
      msg: "加载中，请稍等...", // 提示语
      form: {
        id: "",
        report: "",
      },
      base64: "",
      shareImg: true,
    };
  },
  onLoad(e) {
    this.form.id = e.id;
    this.shareImg = eval(e.shareImg);
    setTimeout(() => {
      this.show = true;
      uni.showLoading({
        title: "图片生成中...",
      });
      this.renderToCanvas();
    }, 1000);
  },
  methods: {
    // 加载图片样式
    renderToCanvas() {
      let setData = this.$store.state.reportDetail;
      if (setData && setData.id) {
        let arr = [];
        if (setData.repair) {
          setData.repair.map((item, index) => {
            let el = index + 1 + "." + item.repair;
            arr.push(el);
          });
          arr = arr.join(";");
        }
        setData.repair = arr;
        let dom_ = wxml(this.$store.state.reportDetail);
        const _style = style(this.screenWidth, this.canvasWidth, this.canvasHeight);
        Object.keys(_style).forEach((i) => {
          const newStyle = {};
          Object.keys(_style[i]).forEach((j) => {
            const kebabCaseKey = j.replace(/([A-Z])/g, "-$1").toLowerCase();
            const value = _style[i][j];
            newStyle[kebabCaseKey] = typeof value === "number" ? value + "px" : value;
          });
          _style[i] = newStyle;
        });
        // #ifdef H5
        this.htmlToImage = dom_;
        const styleSheet = document.createElement("style");
        let css = "";
        for (const selector in _style) {
          css += `.${selector} { `;
          for (const property in _style[selector]) {
            css += `${property}: ${_style[selector][property]}; `;
          }
          css += `} \n`;
        }
        styleSheet.innerText = css;
        document.head.appendChild(styleSheet);
        // #endif
        // #ifdef APP-PLUS
        Object.keys(_style).forEach((i) => {
          const regex = new RegExp(`(class="${i}")`, "g");
          let css = "";
          for (const property in _style[i]) {
            css += `${property}: ${_style[i][property]}; `;
          }
          dom_ = dom_.replace(regex, `$1 style="${css}"`);
        });
        this.htmlToImage = dom_;
        // #endif
        setTimeout(() => {
          uni.hideLoading();
        }, 1000);
      }
    },
    // 转换图片
    renderFinish(base64) {
      this.base64 = base64;
    },
    // 保存为图片
    extraImage() {
      if (!this.show || !this.base64) {
        uni.showToast({
          title: "海报生成失败",
          icon: "none",
        });
        return;
      }
      const token = uni.getStorageSync("userInfo").token;
      uni.uploadFile({
        url: `${baseUrl}/common/upload`,
        filePath: this.base64,
        name: "base64",
        formData: {
          token,
          base64: this.base64
        },
        success: (res1) => {
          let result = JSON.parse(res1.data);
          if (result.code == 1) {
            this.form.report = result.data.fullurl;
            this.$https.post("/warranty/edit_report", this.form).then((res) => {
              uni.showToast({
                title: res.msg,
                duration: 1500,
                icon: "none",
                success: () => {
                  // #ifdef APP-PLUS
                  uni.downloadFile({
                    url: this.form.report,
                    success: (down) => {
                      if (down.statusCode === 200) {
                        this.saveIMg(down.tempFilePath);
                      }
                    },
                  });
                  // #endif
                  // #ifdef H5
                  uni.navigateBack({
                    delta: 1,
                  });
                  // #endif
                },
              });
            });
          } else {
            uni.showToast({
              title: result.msg,
              duration: 1500,
              icon: "none",
            });
          }
        },
        fail: () => {
          uni.showToast({
            title: "上传失败",
            duration: 1500,
            icon: "error",
          });
        },
      });
    },
    // 保存到相册
    async saveIMg(tempFilePath) {
      uni.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: async () => {
          uni.showModal({
            content: "图片已保存，请在相册查看！",
            showCancel: false,
            confirmText: "确定",
            confirmColor: "#333",
            success: () => {
              uni.navigateBack({
                delta: 1,
              });
            },
          });
        },
      });
    },
  },
};
</script>
<style>
page {
  overflow: scroll;
}
</style>
<style lang="scss" scoped>
.share-page {
  background: #fff;
  position: relative;
  min-height: 100vh;
  width: 650px;
  height: 1200px;
  .msg-box {
    display: flex;
    align-items: center;
    text-align: center;
    justify-content: center;
    flex-direction: column;
  }

  .share-page-box {
    margin: 40rpx auto;
    position: relative;
    overflow: hidden;
    box-shadow: 0rpx 6rpx 20rpx 6rpx rgba(0, 0, 0, 0.2);
  }

  .noneText {
    display: flex;
    justify-content: center;
    align-items: center;
    color: #969699;
    margin: 15px 0;
  }

  .share-page-btn {
    padding: 0 20px;
    .btn-big {
      margin: 15px 0;
      background: #1a66ff;
      color: #fff;
      width: 100%;
      padding: 5px;
    }
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
